package com.sunxu.jvm.classloader;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author 孙许
 * @version 1.0
 * @date 2020/7/20 22:58
 */
public class MyClassLoader extends ClassLoader {

    private String name;

    public MyClassLoader(String name) {
      this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    protected Class<?> findClass(String name) {
        byte[] data = loadClassData(name);
        return defineClass(name, data, 0, data.length);
    }

    private byte[] loadClassData(String clsName) {
        String path = clsName.replace(".", "/");
        path = "/Users/sunxu/Documents/workspace/idea-workspace/jvm-learning/out/production/myclasses/" + path + ".class";
        File file = new File(path);
        byte[] data = null;
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             FileInputStream in = new FileInputStream(file)) {
            int a;
            while ((a = in.read()) != -1) {
                out.write(a);
            }
            data = out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
}
